#include "MediaUdpClient.h"
#include "MsgQueueManage.h"
#include <log.h>
#include<iostream>
#include<cstring>


namespace Media{

std::map<std::string, MediaUdpClient *>   MediaUdpClient::sm_objectMap;
std::recursive_mutex 		              MediaUdpClient::sm_mapMutex;


MediaUdpClient *MediaUdpClient::instance(std::string svrAddr)
{
    std::lock_guard<std::recursive_mutex> guard(sm_mapMutex);
    
	if(sm_objectMap.find(svrAddr) == sm_objectMap.end())
	{
		sm_objectMap[svrAddr] = new MediaUdpClient(svrAddr);
	}

	return sm_objectMap[svrAddr];
}


MediaUdpClient::MediaUdpClient(std::string svrAddr) 
{   
    m_svrAddr = svrAddr;
}

MediaUdpClient::~MediaUdpClient() 
{   
    if(m_clientSockfd > 0)
    {
        close(m_clientSockfd);
    }
}

bool MediaUdpClient::creatSocketConnect(uint16_t port)
{
    std::lock_guard<std::mutex> guard(m_connectMutex);
    
    if(m_connetStatus)
    {
        return true;
    }
    
	
	memset(&m_svrSocketInfo, 0, sizeof(m_svrSocketInfo));
	
	m_svrSocketInfo.sin_family = AF_INET;//设置为IP通信
	m_svrSocketInfo.sin_addr.s_addr = inet_addr(m_svrAddr.c_str());//服务器IP地址
	m_svrSocketInfo.sin_port = htons(port); //服务器端口号
	
	//创建客户端套接字 IPv4 tcp
	if((m_clientSockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
	{
		LOG_PrintError("socket error");
		return false;
	}	

	LOG_PrintInfo("creatSocketUdp success,m_svrAddr:%s\n", m_svrAddr.c_str());

	m_connetStatus = true;

	//m_thread.start([this](Fdt::Thread *thread){this->ThreadProc(thread);}); //启动单独线程接收数据


	return true;
}

bool MediaUdpClient::destroySocketConnect(uint16_t port)
{
    std::lock_guard<std::mutex> guard(m_connectMutex);
    if(m_connetStatus && m_clientSockfd > 0)
    {
        close(m_clientSockfd);
        m_connetStatus = false;

        LOG_PrintInfo("MediaUdpClient destroySocketConnect success,m_svrAddr:%s\n", m_svrAddr.c_str());
    }

    return true;
}


// 发送数据的方法  
bool MediaUdpClient::sendData(const char* data, size_t length)
{  
   if(m_clientSockfd < 0)
   {
        LOG_PrintError("m_svrAddr:%s, socket fd error\n", m_svrAddr.c_str());
		return false;
   }

   printf("MediaUdpClient::sendData=");
   for(size_t i = 0; i < length; ++i)
   {
        printf(" %02x", data[i]);
   }
   printf("\n");
   
   int iRet = sendto(m_clientSockfd, data, length, 0, (const struct sockaddr*)&m_svrSocketInfo, sizeof(m_svrSocketInfo));  
   if (iRet == -1)
   {  
       LOG_PrintError("sendto failed\n");  
       return false;  
   }  
   
   return true;  
}


void MediaUdpClient::ThreadProc(Fdt::Thread *thread)
{
    thread->setPriority(Fdt::PRIORITY_NORMAL, Fdt::POLICY_RR);

    char recvBuf[RECEIVE_LEN];//数据接收缓冲区
    int len = 0;
    while (thread->running())
    {
        if(!m_connetStatus)
        {
            thread->sleep(100);
            continue;
        } 

        //从服务端接受消息
        memset(recvBuf, 0, sizeof(recvBuf));
        
        thread->sleep(5);     
    }

    return;
}


}


